const {app, Menu, Tray} = require("electron");
const path = require("path");
const {enableAutoStart} = require("./auto_start");
const {disableAutoStart} = require("./auto_start");
const {store} = require("./config");
const {createMainWindow} = require("./window");
const {openCoffee} = require("./window");
const {Config} = require("./config")

let tray;

let openEye = path.join(__dirname, "assets/eye_open.png");
let closeEye = path.join(__dirname, "assets/eye_close.png");

/**
 * 创建并设置托盘中的眼睛
 * @param sleepCB 20分钟到了，该休息了
 */
async function setEye(sleepCB) {
    tray = new Tray(openEye);
    tray.setToolTip("放松你的眼睛");
    const menu = Menu.buildFromTemplate([
        {
            label: "暂不提示",
            type: "checkbox",
            checked: Config.pauseTips,
            click: function () {
                Config.pauseTips = !Config.pauseTips;
            }
        },
        {
            label: "开机启动",
            type: "checkbox",
            checked: store.get(Config.enableAutoStartKEY, false),
            click: function () {
                if (app.isPackaged) {
                    let opened = store.get(Config.enableAutoStartKEY, false);
                    if (opened) {
                        disableAutoStart()
                    } else {
                        enableAutoStart()
                    }
                }
            }
        },
        {
            label: "请作者喝可乐",
            click: openCoffee,
        },
        {
            label: "退出",
            role: "quit",
        }
    ])
    tray.setContextMenu(menu)
    tray.on("click", () => createMainWindow())
    if (process.platform === "darwin") {
        startCountdown()
    }
    await startBlink()
}

/**
 * 开始托盘中的倒计时
 */
function startCountdown() {
    const sleepT = Config.sleepT;
    let current = sleepT;
    tray.setTitle(` ${current}分钟`);
    setInterval(() => {
        current--;
        if (current === 0) {
            current = sleepT;
            tray.setTitle(" 放松你的眼睛");
        } else {
            tray.setTitle(` ${current}分钟`);
        }
    }, 1000 * 60);
}

/**
 * 开始眨眼任务
 */
async function startBlink() {
    // 5-10随机整数
    function time() {
        return Math.floor(Math.random() * 10) + 5
    }

    function blink() {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                tray.setImage(closeEye)
                setTimeout(() => {
                    tray.setImage(openEye)
                    resolve()
                }, 500)
            }, time() * 1000)
        })
    }

    while (true) {
        await blink()
    }
}

exports.setEye = setEye;
